<?php
namespace Plu\Library\Services\Platform\Live;

use Plu\Library\Models\Tga\Live\CollegeRooms as CollegeRoomsModel,
    Plu\Library\Services\Utility\NumberService;

class LiveCollegeService extends LiveService {
    //城市筛选
    private $cities = [];

    private $excities = [];

    //省
    private $provinces = [];

    private $exprovinces = [];

    //college
    private $colleges = [];

    private $excolleges = [];

    private $parentColleges = [];

    private $exparentColleges = [];

    public function __construct() {
        parent::__construct();
    }

    /**
     * 设定需要获取指定的游戏id
     */
    public function setCities($ids) {
        if (!is_array($ids)) {
            $ids = array($ids);
        }
        $cities = NumberService::toNumberList($ids);

        //merge
        $this->cities = array_values(array_unique(array_merge($this->cities, $cities)));

        return $this;
    }

    public function setExcities($ids) {
        if (!is_array($ids)) {
            $ids = array($ids);
        }

        $cities = NumberService::toNumberList($ids);

        $cities = array_values(array_unique(array_merge($cities, $this->excities)));

        $this->excities = $cities;

        return $this;
    }

    public function setProvinces($ids) {
        if (!is_array($ids)) {
            $ids = array($ids);
        }
        $ids = NumberService::toNumberList($ids);

        //merge
        $this->provinces = array_values(array_unique(array_merge($this->provinces, $ids)));

        return $this;
    }

    public function setExprovinces($ids) {
        if (!is_array($ids)) {
            $ids = array($ids);
        }

        $ids = NumberService::toNumberList($ids);

        $ids = array_values(array_unique(array_merge($ids, $this->exprovinces)));

        $this->exprovinces = $ids;

        return $this;
    }

    //TODO  
    // 需要从redis检测学院是否存在
    public function setColleges($ids) {
        if (!is_array($ids)) {
            $ids = array($ids);
        }
        $ids = NumberService::toNumberList($ids);

        //merge
        $this->colleges = array_values(array_unique(array_merge($this->colleges, $ids)));

        return $this;
    }

    public function setExcolleges($ids) {
        if (!is_array($ids)) {
            $ids = array($ids);
        }

        $ids = NumberService::toNumberList($ids);

        $ids = array_values(array_unique(array_merge($ids, $this->excolleges)));

        $this->excolleges = $ids;

        return $this;
    }

    public function setParentColleges($ids) {
        if (!is_array($ids)) {
            $ids = array($ids);
        }
        $ids = NumberService::toNumberList($ids);

        //merge
        $this->parentColleges = array_values(array_unique(array_merge($this->parentColleges, $ids)));

        return $this;
    }

    public function setExparentColleges($ids) {
        if (!is_array($ids)) {
            $ids = array($ids);
        }

        $ids = NumberService::toNumberList($ids);

        $ids = array_values(array_unique(array_merge($ids, $this->exparentColleges)));

        $this->exparentColleges = $ids;

        return $this;
    }

    /**
     * 重置搜索条件
     */
    public function reset() {
        $this->sortby           = 'top';
        $this->games            = [];
        $this->exgames          = [];
        $this->domains          = [];
        $this->exdomains        = [];
        $this->roomIds          = [];
        $this->exroomIds        = [];
        $this->uids             = [];
        $this->exuids           = [];
        $this->roomTags         = [];
        $this->exroomTags       = [];
        $this->params           = [];
        $this->strictness       = false;
        $this->cities           = [];
        $this->excities         = [];
        $this->provinces        = [];
        $this->exprovinces      = [];
        $this->colleges         = [];
        $this->excolleges       = [];
        $this->parentColleges   = [];
        $this->exparentColleges = [];

        $this->isBroadcast = true;
        $this->filter      = 0;

        $this->formatted   = true;

        return $this;
    }

    /**
     * 计算guid
     */
    private function getGuid($params = array()) {
        $p = array(
            $this->sortby,
            $this->games,
            $this->exgames,
            $this->domains,
            $this->exdomains,
            $this->roomIds,
            $this->exroomIds,
            $this->uids,
            $this->exuids,
            $this->roomTags,
            $this->exroomTags,
            $this->params,
            $this->isBroadcast,
            $this->filter,
            $this->formatted,
            $this->strictness,
            $this->cities,
            $this->excities,
            $this->provinces,
            $this->exprovinces,
            $this->colleges,
            $this->excolleges,
            $this->parentColleges,
            $this->exparentColleges
        );

        $p = array_merge($p, $params);

        return md5(serialize($p));
    }

    /**
     * 根据相关条件获取直播信息数据
     *
     * @param $start_index 
     * @param $max_results
     * @param $games   查询指定的游戏
     * @param $exgames 排除指定的游戏
     * @param $channels 查询指定的房间
     * @param $excludes 排除指定的房间
     * @param $isdomain default true  传入的channels或者excludes是否是domain，false为roomids
     * @param $is_broadcast default true 默认只搜索在线房间
     * @param $filter 过滤数据 1 美女 2 kespa 4 只含有vid的直播
     */
    public function getStreams($start_index = 0, $max_results = 50, $cacheTime = null) {
        if (is_null($cacheTime)) {
            $cacheTime = self::CACHE_TIME;
        }

        $cacheHandler = $this->getCacheHandler();
        $now = time();
        if ($cacheTime > 0) {
            $hash = $this->getGuid(func_get_args());
            $guid = sprintf("tgalives_%s", $hash);
            list($streams, $exptime) = $cacheHandler->get($guid);

            if (is_numeric($exptime) && (($now - $exptime) >= $cacheTime)) {
                $streams = array();//reset
            }
        } else {
            $streams = array();
        }

        if (!empty($streams) && is_array($streams)) {
            return $streams;
        }

        if ($this->strictness && empty($this->roomTags)) {
            return array(0, []);
        }

        $roomModel = new CollegeRoomsModel;

        $roomModel->setGames($this->games)
            ->setExgames($this->exgames)
            ->setRoomIds($this->roomIds)
            ->setExroomIds($this->exroomIds)
            ->setBroadcastStatus($this->isBroadcast)
            ->setFilter($this->filter)
            ->setParams($this->params)
            ->setColleges($this->colleges)
            ->setExcolleges($this->excolleges)
            ->setParentColleges($this->parentColleges)
            ->setExparentColleges($this->exparentColleges)
            ->setCities($this->cities)
            ->setExcities($this->excities)
            ->setProvinces($this->provinces)
            ->setExprovinces($this->exprovinces);
        
        list($totalCount, $items) = $roomModel->getStreams($start_index, $max_results, $this->sortby, $this->roomTags, $this->exroomTags);

        if ($this->formatted) {
            $items = $this->format($items);
        }
        
        $data = array($totalCount, $items);

        if ($cacheTime > 0) {
            $cacheHandler->save($guid, array($data, $now), $cacheTime);
        }

        return $data;
    }

    /**
     * 格式化数据
     */
    private function format($rooms) {
        $data = [];
        array_walk($rooms, function($room) use(&$data) {
            $data[] = array(
                "preview"  => $room['preview'],
                "preview2"  => $room['preview2'],
                "game"     => array(
                    'Id'   => $room['gameid'],
                    'id'   => $room['gameid'],
                    'Name' => $room['gamename'],
                    'name' => $room['gamename'],
                    'tag'  => $room['gametag']
                ),
                "channel"  => array(
                    "id"                 => $room['id'],
                    "name"               => $room['name'],
                    "avatar"             => $room['avatar'],
                    "grade"              => (int)$room['grade'],
                    "url"                => $room['domain'],
                    "status"             => $room['status'],
                    'broadcast_begin'    => $room['broadcast_begin'],
                    'broadcast_duration' => $room['broadcast_duration'],
                    "videos"             => $room['videos'], //always 0
                    "_type"              => $room['_type'],
                    "_subtype"           => $room['_subtype'],//主播类型
                    "belle"              => $room['belle'],
                    "domain"             => $room['domain'],
                    "flowers"            => $room['flowers'],
                    'followers'          => $room['followers'],
                    'glamours'           => $room['glamours'],
                    'tag'                => $room['tag'],
                    'vid'                => (int)$room['vid'],
                    'weight'             => (int)$room['weight'],
                    'live_source'        => (int)$room['live_source'],
                    'stream_types'       => (int)$room['stream_types']
                ),
                "viewers" => intval($room['views'])
            );
        });

        return $data;
    }
}
?>
